/**
 * 
 */
package com.cipe.cmrs.controllers.payment;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;

import com.cipe.cmrs.bean.PaymentRequestBean;
import com.cipe.cmrs.filter.SessionObjectFilter;
import com.cipe.cmrs.util.SessionHistoryRepository;

/**
 * @author Incepio
 * 
 */
@Controller
@RequestMapping("/secure/showEditPaymentrequest.do")
public class EditPaymentRequestController extends AbstractPaymentController {
    /**
	 * 
	 */
    private static final long serialVersionUID = 3480388481687538109L;

    private static final String FORM_VIEW = "payment/editPaymentrequest";

    public EditPaymentRequestController() {
        setFormView(FORM_VIEW);
        setSuccessView(FORM_VIEW);
    }

    @ModelAttribute(COMMAND_NAME)
    public PaymentRequestBean getCommand(@RequestParam Integer id) {
        return paymentrequestService.getPaymentRequestbean(id);
    }

    protected Map<String, Object> getReferenceData(PaymentRequestBean bean, HttpServletRequest request) {
        Map<String, Object> map = super.getReferenceData(bean, request);
        map.put("createdByCurrentUser", bean.getCreatedBy() == null || getUserId(request) == bean.getCreatedById());
        // By Andy: UAT-040 - Editing Payment Request - Payment Request can only
        // be edited IF status is "New" or "Rejected"
        boolean canEdit = getText("status.payment.process.new").equals(bean.getStatusCode())
            || getText("status.payment.process.rejected").equals(bean.getStatusCode());
        map.put("canEdit", canEdit);
        return map;
    }
    
    @RequestMapping(method = RequestMethod.POST)
    public ModelAndView onSubmit(@ModelAttribute(COMMAND_NAME) PaymentRequestBean bean, BindingResult result,
        HttpServletRequest request, SessionStatus status) {
        ModelAndView mav = null;    
            try {
                String addEditPayee = request.getParameter(getText("editPaymentrequest.button.addEditPayee"));
                if (StringUtils.hasText(addEditPayee)) {
                    request.getSession().setAttribute(SessionObjectFilter.UNSAVED_PAYMENT, bean);
                    String paymentUrl = (String) request.getSession().getAttribute(SessionHistoryRepository.CURR_URL);
                    if (bean.getPayeeId() != null && bean.getPayeeId() > 0) {
                        return new ModelAndView("redirect:showEditPayeePersonalInfo.do?id=" + bean.getPayeeId() + "&paymentUrl=" + paymentUrl);
                    } else {
                        return new ModelAndView("redirect:showAddPayee.do?paymentUrl=" + paymentUrl);
                    }
                }
                String nextAction = request.getParameter(getText("name.button.nextaction"));
                if (StringUtils.hasText(nextAction)) {
                    bean = paymentrequestService.processPaymentRequest(bean, getUserId(request));
                } else {
                    String action = request.getParameter(DEFAULT_SUBMIT_NAME);
                    if (getText("editPaymentrequest.label.cancel").equalsIgnoreCase(action)) {
                        bean = paymentrequestService.cancelPaymentRequest(bean, getUserId(request), null);
                    } else if (getText("editPaymentrequest.label.reject").equalsIgnoreCase(action)) {
                        bean = paymentrequestService.rejectPaymentRequest(bean, getUserId(request));
                    } else if (getText("editPaymentrequest.label.prResubmit").equals(action)) {
                        bean = paymentrequestService.resubmitPayment(bean, getUserId(request));
                    } else if (getText("editPaymentrequest.label.prCancel").equalsIgnoreCase(action)) {
                        bean = paymentrequestService.setCancelRequested(bean, getUserId(request));
                    } else if (getText("editPaymentrequest.button.save").equalsIgnoreCase(action)) {
                        bean = paymentrequestService.savePaymentrequest(bean, getUserId(request));
                    }
                }

                saveMessage(request, getText("editPaymentrequest.message.success"));
                status.setComplete();
                mav = getSuccessView(bean, request).addObject(COMMAND_NAME, bean);
            } catch (Exception e) {
                e.printStackTrace();
                logger.error(getText("error.transaction"), e);
                saveError(request, getText("error.transaction"));
                mav = getFormView(bean, request);
            }
        
        return mav;
    }

}
